package com.qingzhou.common.security.impl;

import cn.hutool.core.convert.Convert;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Condition;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.Context;
import org.noear.solon.validation.annotation.NoRepeatSubmit;
import org.noear.solon.validation.annotation.NoRepeatSubmitChecker;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * 分布式锁
 */
@Component
@Condition(onClass = RedissonClient.class)
public class NoRepeatSubmitCheckerImpl implements NoRepeatSubmitChecker {

    @Inject
    RedissonClient redissonClient;

    /**
     * 针对于 NoRepeatSubmit默认使用本地延时锁，定制为分布式锁
     * @param anno
     * @param ctx
     * @param submitHash
     * @param limitSeconds
     * @return
     */
    @Override
    public boolean check(NoRepeatSubmit anno, Context ctx, String submitHash, int limitSeconds) {
        boolean b;
        try {
            b = redissonClient.getLock(submitHash).tryLock(Convert.toInt(limitSeconds, 1), TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            b = true;
        }
        return b;
    }

}
